package co.flante.dao;

import co.flante.entities.Event;
import co.flante.services.EntityManagerProvider;
import com.google.inject.Inject;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.List;

/**
 * <p>Title: EventManager</p>
 * <p>Description: Fetch and persist events to a data store (JPA backed database).</p>
 * @author Mike Haas, Aaron Cook, Kyle Kolstad
 * @email michael.haas.@my.uwrf.edu, aaron.cook@my.uwrf.edu, kyle.kolstad@my.uwrf.edu
 * @date 12/03/2013
 */
public class EventManager {
    @Inject
    EntityManagerProvider entityManagerProvider;

    /**
     * Persist an event object to the database.
     *
     * @param event an Event object
     */
    public void create(Event event) {
        EntityManager em = entityManagerProvider.get();

        try {
            em.getTransaction().begin();
            em.persist(event);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }

    /**
     * This will find a single Event identifed by the id from the database.
     *
     * @param id the id of the event to fetch from the database
     * @return A single Event object if identified by id
     */
    public Event findById(Long id) {
        EntityManager em = entityManagerProvider.get();
        Event event = null;

        try {
            TypedQuery<Event> q = em.createQuery("from Event e where e.id = :id", Event.class).setParameter("id", id);
            event = q.getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }

        return event;
    }

    /**
     * Return all events from the database. Truthfully, this is actually set to a hard limit of 25 as to not bog
     * down the REST request. However, for all intensive purposes it is fetching "All"
     * @return A list of the events
     */
    public List<Event> findAll() {
        EntityManager em = entityManagerProvider.get();
        List<Event> events = null;

        try {
            TypedQuery<Event> q = em.createQuery("from Event e order by e.created desc", Event.class).setMaxResults(25);
            events = q.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }

        return events;
    }
}
